<template>
  <div class="dashboard-container">
    <!-- 页面头部 -->
    <div class="dashboard-header">
      <h1>工作台</h1>
      <div class="user-info">
        <span class="welcome-text">欢迎回来，{{ userInfo.name }}</span>
        <span class="position-info">{{ userInfo.position_name }} - {{ userInfo.dept_name }}</span>
        <el-button type="text" @click="refreshData" class="refresh-btn">
          <el-icon><ElementPlusIconsVue.Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 数据加载状态 -->
    <el-empty v-if="loading" description="数据加载中..." style="padding: 40px 0">
      <template #image>
        <el-icon :size="60"><ElementPlusIconsVue.Loading /></el-icon>
      </template>
    </el-empty>

    <!-- 统计概览卡片 -->
    <el-row v-if="!loading" :gutter="20" class="overview-row">
      <el-col :span="6" v-for="(item, index) in dashboardData.stats.overview" :key="index">
        <el-card class="overview-card" @click="handleCardClick(item)">
          <div class="overview-content">
            <div class="overview-icon" :style="{ backgroundColor: item.color }">
              <el-icon :size="24">
                <component :is="getIcon(item.icon)" />
              </el-icon>
            </div>
            <div class="overview-info">
              <div class="overview-title">{{ item.name }}</div>
              <div class="overview-number">{{ item.value }}</div>
              <div class="overview-trend" v-if="item.trend">
                <el-icon :size="12" :class="getTrendClass(item.trend.type)">
                  <component
                    :is="
                      item.trend.type === 'up'
                        ? ElementPlusIconsVue.ArrowUp
                        : item.trend.type === 'down'
                          ? ElementPlusIconsVue.ArrowDown
                          : ElementPlusIconsVue.Minus
                    "
                  />
                </el-icon>
                <span>{{ item.trend.value }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row v-if="!loading" :gutter="20" class="content-row">
      <!-- 左侧内容区域 -->
      <el-col :span="16">
        <!-- 财务统计 -->
        <el-card class="content-card">
          <template #header>
            <div class="card-header">
              <h3>财务数据</h3>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col :span="8" v-for="(item, index) in dashboardData.stats.finance" :key="index">
              <div class="finance-item">
                <div class="finance-icon" :style="{ color: item.color }">
                  <el-icon :size="20"><component :is="getIcon(item.icon)" /></el-icon>
                </div>
                <div class="finance-info">
                  <div class="finance-title">{{ item.name }}</div>
                  <div class="finance-count">{{ item.count }} 笔</div>
                  <div class="finance-amount">¥ {{ item.amount_format }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 合同金额统计（按日期区间） -->
        <el-card class="content-card">
          <template #header>
            <div class="card-header">
              <h3>合同金额统计</h3>
            </div>
          </template>

          <!-- 日期区间选择器 -->
          <el-button-group class="period-selector" style="margin-bottom: 16px">
            <el-button
              :type="selectedPeriod === 'today' ? 'primary' : ''"
              @click="changePeriod('today')"
            >
              本日
            </el-button>
            <el-button
              :type="selectedPeriod === 'week' ? 'primary' : ''"
              @click="changePeriod('week')"
            >
              本周
            </el-button>
            <el-button
              :type="selectedPeriod === 'month' ? 'primary' : ''"
              @click="changePeriod('month')"
            >
              本月
            </el-button>
            <el-button
              :type="selectedPeriod === 'quarter' ? 'primary' : ''"
              @click="changePeriod('quarter')"
            >
              本季度
            </el-button>
          </el-button-group>

          <!-- 图表展示 -->
          <div ref="contractAmountChart" class="chart-container"></div>

          <!-- 数据表格 -->
          <el-table
            v-if="getSelectedFinanceData() && getSelectedFinanceData().length > 0"
            :data="getSelectedFinanceData()"
            style="margin-top: 16px"
            size="small"
            border
          >
            <el-table-column prop="contract_type" label="合同类型" width="180"></el-table-column>
            <el-table-column
              prop="contract_count"
              label="合同数"
              width="100"
              align="right"
            ></el-table-column>
            <el-table-column
              prop="contract_amount_format"
              label="合同金额"
              width="160"
              align="right"
            >
              <template #default="scope">
                <span style="font-weight: 500; color: #4facfe">
                  ¥{{ scope.row.contract_amount_format }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="payment_amount_format"
              label="到账金额"
              width="160"
              align="right"
            >
              <template #default="scope">
                <span style="font-weight: 500; color: #fa709a">
                  ¥{{ scope.row.payment_amount_format }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="trend" label="趋势" width="120" align="center">
              <template #default="scope">
                <div v-if="scope.row.trend" class="trend-item">
                  <el-icon :size="14" :class="getTrendClass(scope.row.trend.type)">
                    <component
                      :is="
                        scope.row.trend.type === 'up'
                          ? ElementPlusIconsVue.ArrowUp
                          : scope.row.trend.type === 'down'
                            ? ElementPlusIconsVue.ArrowDown
                            : ElementPlusIconsVue.Minus
                      "
                    />
                  </el-icon>
                  <span :class="getTrendClass(scope.row.trend.type)">
                    {{ scope.row.trend.value }}%
                  </span>
                </div>
                <span v-else class="text-gray-400">--</span>
              </template>
            </el-table-column>
          </el-table>

          <!-- 无数据提示 -->
          <div v-else class="no-data">暂无数据</div>
        </el-card>

        <!-- 业务统计图表 -->
        <el-row :gutter="20" class="chart-row">
          <el-col :span="12">
            <el-card class="content-card">
              <template #header>
                <div class="card-header">
                  <h3>合同类型分布</h3>
                </div>
              </template>
              <div ref="contractChart" class="chart-container"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="content-card">
              <template #header>
                <div class="card-header">
                  <h3>客户类型分布</h3>
                </div>
              </template>
              <div ref="customerChart" class="chart-container"></div>
            </el-card>
          </el-col>
        </el-row>

        <!-- 案件阶段统计 -->
        <el-card v-if="hasLawcaseStats" class="content-card">
          <template #header>
            <div class="card-header">
              <h3>案件各阶段分布</h3>
            </div>
          </template>
          <div ref="lawcaseChart" class="chart-container large"></div>
        </el-card>
      </el-col>

      <!-- 右侧内容区域 -->
      <el-col :span="8">
        <!-- 快捷入口 -->
        <el-card class="content-card">
          <template #header>
            <div class="card-header">
              <h3>快捷入口</h3>
            </div>
          </template>
          <el-row :gutter="16">
            <el-col v-for="(item, index) in dashboardData.quick_actions" :key="index" :span="8">
              <div class="quick-action-item" @click="handleQuickActionClick(item.url)">
                <div class="quick-action-icon" :style="{ backgroundColor: item.color }">
                  <el-icon><component :is="getIcon(item.icon)" /></el-icon>
                </div>
                <div class="quick-action-name">{{ item.name }}</div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 待办事项 -->
        <el-card class="content-card">
          <template #header>
            <div class="card-header">
              <h3>待办事项</h3>
            </div>
          </template>
          <div class="pending-list">
            <div
              v-for="(item, index) in dashboardData.stats.pending"
              :key="index"
              class="pending-item"
            >
              <el-tag :type="getPriorityType(item.priority)" class="priority-tag">
                {{ getPriorityText(item.priority) }}
              </el-tag>
              <span class="pending-name">{{ item.name }}</span>
              <span class="pending-count">{{ item.count }}</span>
            </div>
            <div v-if="dashboardData.stats.pending.length === 0" class="no-data">暂无待办事项</div>
          </div>
        </el-card>

        <!-- 日程安排 -->
        <el-card class="content-card">
          <template #header>
            <div class="card-header">
              <h3>今日日程</h3>
            </div>
          </template>
          <div class="schedule-list">
            <div
              v-for="(item, index) in dashboardData.stats.schedule.today"
              :key="index"
              class="schedule-item"
            >
              <div class="schedule-time">
                {{ item.start_time_format }} - {{ item.end_time_format }}
              </div>
              <div class="schedule-content">{{ item.content }}</div>
              <el-tag v-if="item.is_urgent" type="danger" size="small" class="urgent-tag">
                紧急
              </el-tag>
            </div>
            <div v-if="dashboardData.stats.schedule.today.length === 0" class="no-data">
              今日暂无日程
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 工作效率统计（领导可见） -->
    <el-row v-if="!loading && dashboardData.permissions.is_leader" :gutter="20" class="content-row">
      <el-col :span="24">
        <el-card class="content-card">
          <template #header>
            <div class="card-header">
              <h3>部门工作效率排名</h3>
            </div>
          </template>
          <div ref="departmentChart" class="chart-container large"></div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue'
  import * as echarts from 'echarts'
  import * as ElementPlusIconsVue from '@element-plus/icons-vue'
  import { homeApi } from '@/api/home'
  import type { DashboardStats } from '@/types/home'
  import { useRouter } from 'vue-router'

  // 路由实例
  const router = useRouter()

  // 图表实例
  const contractChart = ref<HTMLElement>()
  const customerChart = ref<HTMLElement>()
  const lawcaseChart = ref<HTMLElement>()
  const departmentChart = ref<HTMLElement>()
  const contractAmountChart = ref<HTMLElement>()

  // 图表对象
  let contractChartInstance: echarts.ECharts | null = null
  let customerChartInstance: echarts.ECharts | null = null
  let lawcaseChartInstance: echarts.ECharts | null = null
  let departmentChartInstance: echarts.ECharts | null = null
  let contractAmountChartInstance: echarts.ECharts | null = null

  // 当前选择的日期区间
  const selectedPeriod = ref<'today' | 'week' | 'month' | 'quarter'>('today')

  // 获取当前选中的财务数据
  const getSelectedFinanceData = () => {
    const dataMap = {
      today: dashboardData.value.stats.finance_by_period?.today || [],
      week: dashboardData.value.stats.finance_by_period?.week || [],
      month: dashboardData.value.stats.finance_by_period?.month || [],
      quarter: dashboardData.value.stats.finance_by_period?.quarter || [],
    }
    return dataMap[selectedPeriod.value]
  }

  // 数据状态
  const loading = ref(true)
  const dashboardData = ref<DashboardStats>({
    user_info: {
      id: 0,
      name: '',
      username: '',
      did: 0,
      position_id: 0,
      dept_name: '',
      position_name: '',
    },
    stats: {
      overview: [],
      finance: [],
      finance_by_period: {
        today: [],
        week: [],
        month: [],
        quarter: [],
      },
      business: {
        new_customers: {
          name: '',
          value: 0,
          type: '',
        },
        new_contracts: {
          name: '',
          value: 0,
          type: '',
        },
        contract_amount: {
          name: '',
          value: 0,
          type: '',
        },
        contract_stats: {
          case_entrust: {
            name: '',
            count: 0,
            amount: 0,
            average: 0,
            amount_format: '',
            average_format: '',
          },
          legal: {
            name: '',
            count: 0,
            amount: 0,
            average: 0,
            amount_format: '',
            average_format: '',
          },
        },
        customer_stats: {
          company: {
            name: '',
            total: 0,
            member: 0,
            non_member: 0,
          },
          individual: {
            name: '',
            total: 0,
            member: 0,
            non_member: 0,
          },
        },
        lawcase_stage_stats: {
          total_count: 0,
          stages: [],
        },
      },
      pending: [],
      schedule: {
        today: [],
        upcoming: [],
        weekly: [],
        statistics: {
          today_count: 0,
          upcoming_count: 0,
          week_total: 0,
          urgent_count: 0,
          month_total: 0,
        },
      },
      messages: {
        latest: [],
        stats: {
          total: 0,
          unread: 0,
          read: 0,
        },
        unread_count: 0,
      },
      comprehensive: {},
    },
    summary: {
      total_items: 0,
      pending_count: 0,
      unread_count: 0,
    },
    quick_actions: [],
    permissions: {
      is_leader: false,
      department_count: 0,
      can_approve: false,
      permission_level: 'staff',
    },
    last_update: 0,
    last_update_format: '',
  })

  // 计算属性
  const userInfo = ref(dashboardData.value.user_info)
  const hasLawcaseStats = ref(false)

  // 获取图标组件
  const getIcon = (iconName: string) => {
    // Element Plus 图标名称映射（使用实际可用的图标）
    const iconMap: Record<string, any> = {
      'pay-circle': ElementPlusIconsVue.CircleCheck,
      'file-done': ElementPlusIconsVue.DocumentChecked,
      'file-add': ElementPlusIconsVue.DocumentAdd,
      user: ElementPlusIconsVue.User,
      'file-text': ElementPlusIconsVue.Document,
      'shopping-cart': ElementPlusIconsVue.ShoppingBag,
      'check-circle': ElementPlusIconsVue.CircleCheck,
      scale: ElementPlusIconsVue.HomeFilled, // 临时替代，实际应该使用合适的图标
      'user-add': ElementPlusIconsVue.User, // 临时替代，实际应该使用合适的图标
      calendar: ElementPlusIconsVue.Calendar,
      edit: ElementPlusIconsVue.Edit,
      document: ElementPlusIconsVue.Document,
    }
    return iconMap[iconName] || ElementPlusIconsVue.User
  }

  // 获取趋势样式类
  const getTrendClass = (trendType: string) => {
    return trendType === 'up' ? 'trend-up' : trendType === 'down' ? 'trend-down' : 'trend-stable'
  }

  // 获取优先级标签类型
  const getPriorityType = (priority: string) => {
    const priorityMap: Record<string, string> = {
      high: 'danger',
      medium: 'warning',
      low: 'info',
    }
    return priorityMap[priority] || 'default'
  }

  // 获取优先级文本
  const getPriorityText = (priority: string) => {
    const priorityMap: Record<string, string> = {
      high: '高',
      medium: '中',
      low: '低',
    }
    return priorityMap[priority] || '普通'
  }

  // 处理卡片点击
  const handleCardClick = (item: any) => {
    // 根据不同的统计项跳转到不同的页面
    switch (item.name) {
      case '案件总量':
        router.push('/lawcase/list')
        break
      case '报销总数':
        router.push('/expense/list')
        break
      case '开票总数':
        router.push('/invoice/list')
        break
      case '收票总数':
        router.push('/ticket/list')
        break
      case '客户总数':
        router.push('/customer/list')
        break
      case '销售合同':
        router.push('/contract')
        break
      case '采购合同':
        router.push('/purchase/list')
        break
      default:
        break
    }
  }

  // 处理快捷入口点击
  const handleQuickActionClick = (url: string) => {
    router.push(url)
  }

  // 初始化图表
  const initCharts = () => {
    // 合同金额趋势图
    if (contractAmountChart.value) {
      contractAmountChartInstance = echarts.init(contractAmountChart.value)
      const financeData = getSelectedFinanceData()

      if (financeData && financeData.length > 0) {
        const contractTypeData = financeData.map(item => item.contract_type)
        const contractAmountData = financeData.map(item => item.contract_amount)
        const paymentAmountData = financeData.map(item => item.payment_amount)

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow',
            },
            formatter: (params: any) => {
              const dataIndex = params[0].dataIndex
              const item = financeData[dataIndex]
              return (
                `${item.contract_type}<br/>合同数: ${item.contract_count} 笔<br/>` +
                `合同金额: ${item.contract_amount_format}<br/>` +
                `到账金额: ${item.payment_amount_format}`
              )
            },
          },
          legend: {
            data: ['合同金额', '到账金额'],
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true,
          },
          xAxis: {
            type: 'category',
            data: contractTypeData,
            axisLabel: {
              rotate: 30,
            },
          },
          yAxis: {
            type: 'value',
            axisLabel: {
              formatter: '¥{value}',
            },
          },
          series: [
            {
              name: '合同金额',
              type: 'bar',
              data: contractAmountData,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#4facfe' },
                  { offset: 1, color: '#00f2fe' },
                ]),
              },
            },
            {
              name: '到账金额',
              type: 'bar',
              data: paymentAmountData,
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#fa709a' },
                  { offset: 1, color: '#fee140' },
                ]),
              },
            },
          ],
        } as any
        contractAmountChartInstance.setOption(option)
      }
    }

    // 合同类型分布图
    if (contractChart.value) {
      contractChartInstance = echarts.init(contractChart.value)
      const contractData = [
        {
          name: dashboardData.value.stats.business.contract_stats.case_entrust.name,
          value: dashboardData.value.stats.business.contract_stats.case_entrust.amount,
        },
        {
          name: dashboardData.value.stats.business.contract_stats.legal.name,
          value: dashboardData.value.stats.business.contract_stats.legal.amount,
        },
      ]

      // 为ECharts配置添加正确的类型断言
      const contractOption = {
        tooltip: {
          trigger: 'item' as const,
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
          orient: 'vertical' as const,
          left: 10,
          data: contractData.map(item => item.name),
        },
        series: [
          {
            name: '合同金额',
            type: 'pie' as const,
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center' as const,
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: contractData,
          },
        ],
      } as any
      contractChartInstance.setOption(contractOption)
    }

    // 客户类型分布图
    if (customerChart.value) {
      customerChartInstance = echarts.init(customerChart.value)
      const customerData = [
        {
          name: dashboardData.value.stats.business.customer_stats.company.name,
          value: dashboardData.value.stats.business.customer_stats.company.total,
        },
        {
          name: dashboardData.value.stats.business.customer_stats.individual.name,
          value: dashboardData.value.stats.business.customer_stats.individual.total,
        },
      ]

      const customerOption = {
        tooltip: {
          trigger: 'item' as const,
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        legend: {
          orient: 'vertical' as const,
          left: 10,
          data: customerData.map(item => item.name),
        },
        series: [
          {
            name: '客户数量',
            type: 'pie' as const,
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: false,
              position: 'center' as const,
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold',
              },
            },
            labelLine: {
              show: false,
            },
            data: customerData,
          },
        ],
      } as any
      customerChartInstance.setOption(customerOption)
    }

    // 案件阶段分布图
    if (
      lawcaseChart.value &&
      dashboardData.value.stats.business.lawcase_stage_stats.stages.length > 0
    ) {
      hasLawcaseStats.value = true
      lawcaseChartInstance = echarts.init(lawcaseChart.value)
      const lawcaseData = dashboardData.value.stats.business.lawcase_stage_stats.stages.map(
        stage => ({
          name: stage.stage_name,
          value: stage.count,
        })
      )

      const lawcaseOption = {
        tooltip: {
          trigger: 'axis' as const,
          axisPointer: {
            type: 'shadow' as const,
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true,
        },
        xAxis: {
          type: 'value' as const,
        },
        yAxis: {
          type: 'category' as const,
          data: lawcaseData.map(item => item.name),
        },
        series: [
          {
            name: '案件数量',
            type: 'bar' as const,
            barWidth: '60%',
            data: lawcaseData.map(item => item.value),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' },
              ]),
            },
          },
        ],
      } as any
      lawcaseChartInstance.setOption(lawcaseOption)
    }

    // 部门工作效率排名图（领导可见）
    if (
      departmentChart.value &&
      dashboardData.value.permissions.is_leader &&
      dashboardData.value.stats.comprehensive.dept_performance?.data.length
    ) {
      departmentChartInstance = echarts.init(departmentChart.value)
      const deptData = dashboardData.value.stats.comprehensive.dept_performance.data

      const deptOption = {
        tooltip: {
          trigger: 'axis' as const,
          axisPointer: {
            type: 'shadow' as const,
          },
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true,
        },
        xAxis: {
          type: 'category' as const,
          data: deptData.map(item => item.dept_name),
          axisLabel: {
            interval: 0,
            rotate: 30,
          },
        },
        yAxis: {
          type: 'value' as const,
          name: '完成任务数',
        },
        series: [
          {
            name: '完成任务数',
            type: 'bar' as const,
            data: deptData.map(item => item.completed_tasks),
            itemStyle: {
              color: function (params: any) {
                const colorList = [
                  '#FF7F50',
                  '#87CEFA',
                  '#DA70D6',
                  '#32CD32',
                  '#6495ED',
                  '#FF69B4',
                  '#B8860B',
                  '#FFA500',
                  '#9370DB',
                  '#98FB98',
                ]
                return colorList[params.dataIndex % colorList.length]
              },
            },
            label: {
              show: true,
              position: 'top' as const,
            },
          },
        ],
      } as any
      departmentChartInstance.setOption(deptOption)
    }
  }

  // 刷新图表
  const resizeCharts = () => {
    contractChartInstance?.resize()
    customerChartInstance?.resize()
    lawcaseChartInstance?.resize()
    departmentChartInstance?.resize()
    contractAmountChartInstance?.resize()
  }

  // 切换日期区间
  const changePeriod = (period: 'today' | 'week' | 'month' | 'quarter') => {
    selectedPeriod.value = period
    // 重新初始化图表
    if (contractAmountChartInstance) {
      contractAmountChartInstance.dispose()
      initCharts()
    }
  }

  // 生成模拟数据
  const generateMockFinanceData = () => {
    const contractTypes = ['销售合同', '采购合同', '劳动合同', '服务合同', '技术合同']
    const mockData = contractTypes.map(type => ({
      name: type,
      contract_type: type,
      contract_count: Math.floor(Math.random() * 20) + 1,
      contract_amount: Math.floor(Math.random() * 1000000) + 10000,
      contract_amount_format: (Math.floor(Math.random() * 1000000) + 10000).toLocaleString(
        'zh-CN',
        { minimumFractionDigits: 2, maximumFractionDigits: 2 }
      ),
      payment_amount: Math.floor(Math.random() * 800000) + 5000,
      payment_amount_format: (Math.floor(Math.random() * 800000) + 5000).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2,
      }),
      trend: {
        type: ['up', 'down', 'stable'][Math.floor(Math.random() * 3)] as 'up' | 'down' | 'stable',
        value: Math.floor(Math.random() * 50) + 1,
      },
    }))
    return mockData
  }

  // 加载数据
  const loadData = async () => {
    loading.value = true
    try {
      const response = await homeApi.getDashboardStats()
      if (response.code === 0 && response.data) {
        dashboardData.value = response.data
        userInfo.value = response.data.user_info
      } else {
        // 如果没有真实数据，使用模拟数据
        dashboardData.value.stats.finance_by_period = {
          today: generateMockFinanceData(),
          week: generateMockFinanceData(),
          month: generateMockFinanceData(),
          quarter: generateMockFinanceData(),
        }
      }
      initCharts()
    } catch (error) {
      // 出错时也使用模拟数据
      dashboardData.value.stats.finance_by_period = {
        today: generateMockFinanceData(),
        week: generateMockFinanceData(),
        month: generateMockFinanceData(),
        quarter: generateMockFinanceData(),
      }
    } finally {
      loading.value = false
    }
  }

  // 刷新数据
  const refreshData = () => {
    // 清除之前的图表实例
    contractChartInstance?.dispose()
    customerChartInstance?.dispose()
    lawcaseChartInstance?.dispose()
    departmentChartInstance?.dispose()
    contractAmountChartInstance?.dispose()
    loadData()
  }

  // 组件挂载时
  onMounted(() => {
    loadData()
    window.addEventListener('resize', resizeCharts)
  })

  // 组件卸载时
  onUnmounted(() => {
    window.removeEventListener('resize', resizeCharts)
    contractChartInstance?.dispose()
    customerChartInstance?.dispose()
    lawcaseChartInstance?.dispose()
    departmentChartInstance?.dispose()
    contractAmountChartInstance?.dispose()
  })
</script>

<style scoped lang="scss">
  .dashboard-container {
    padding: 20px;
    background-color: #f5f7fa;
    min-height: 100vh;
  }

  .dashboard-header {
    margin-bottom: 20px;
    padding: 15px 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .dashboard-header h1 {
    margin: 0;
    font-size: 24px;
    color: #303133;
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 15px;
  }

  .welcome-text {
    font-size: 16px;
    color: #606266;
  }

  .position-info {
    font-size: 14px;
    color: #909399;
  }

  .refresh-btn {
    color: #1890ff;
  }

  .overview-row {
    margin-bottom: 20px;
  }

  .overview-card {
    cursor: pointer;
    transition: all 0.3s ease;
    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
  }

  .overview-content {
    display: flex;
    align-items: center;
    padding: 10px 0;
  }

  .overview-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    margin-right: 16px;
  }

  .overview-info {
    flex: 1;
  }

  .overview-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 8px;
  }

  .overview-number {
    font-size: 24px;
    font-weight: bold;
    color: #303133;
    margin-bottom: 4px;
  }

  .overview-trend {
    display: flex;
    align-items: center;
    font-size: 12px;
  }

  .trend-up {
    color: #f56c6c;
  }

  .trend-down {
    color: #67c23a;
  }

  .trend-stable {
    color: #909399;
  }

  .content-row {
    margin-bottom: 20px;
  }

  .content-card {
    margin-bottom: 20px;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .card-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #303133;
  }

  .finance-item {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #f0f0f0;
    &:last-child {
      border-bottom: none;
    }
  }

  .finance-icon {
    margin-right: 12px;
  }

  .finance-info {
    flex: 1;
  }

  .finance-title {
    font-size: 14px;
    color: #606266;
    margin-bottom: 4px;
  }

  .finance-count {
    font-size: 12px;
    color: #909399;
    margin-bottom: 2px;
  }

  .finance-amount {
    font-size: 18px;
    font-weight: bold;
    color: #e6a23c;
  }

  .chart-row {
    margin-bottom: 20px;
  }

  .chart-container {
    width: 100%;
    height: 300px;
  }

  .chart-container.large {
    height: 400px;
  }

  .period-selector {
    display: flex;
    justify-content: flex-end;
  }

  .trend-item {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 4px;
  }

  .text-gray-400 {
    color: #909399;
  }

  .quick-action-item {
    text-align: center;
    padding: 15px 0;
    cursor: pointer;
    transition: all 0.3s ease;
    &:hover {
      transform: translateY(-3px);
    }
  }

  .quick-action-icon {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #fff;
    margin: 0 auto 8px;
    font-size: 20px;
  }

  .quick-action-name {
    font-size: 14px;
    color: #606266;
  }

  .pending-list {
    max-height: 200px;
    overflow-y: auto;
  }

  .pending-item {
    display: flex;
    align-items: center;
    padding: 10px 0;
    border-bottom: 1px solid #f0f0f0;
    &:last-child {
      border-bottom: none;
    }
  }

  .priority-tag {
    margin-right: 10px;
  }

  .pending-name {
    flex: 1;
    font-size: 14px;
    color: #303133;
  }

  .pending-count {
    font-size: 14px;
    font-weight: bold;
    color: #909399;
  }

  .schedule-list {
    max-height: 250px;
    overflow-y: auto;
  }

  .schedule-item {
    padding: 12px 0;
    border-bottom: 1px solid #f0f0f0;
    position: relative;
    &:last-child {
      border-bottom: none;
    }
  }

  .schedule-time {
    font-size: 12px;
    color: #909399;
    margin-bottom: 4px;
  }

  .schedule-content {
    font-size: 14px;
    color: #303133;
    word-break: break-all;
  }

  .urgent-tag {
    position: absolute;
    top: 12px;
    right: 0;
  }

  .no-data {
    text-align: center;
    color: #909399;
    padding: 20px 0;
  }

  /* 响应式设计 */
  @media (max-width: 1200px) {
    .content-row {
      .el-col-16 {
        width: 100% !important;
      }
      .el-col-8 {
        width: 100% !important;
      }
      .el-col-12 {
        width: 100% !important;
      }
    }
  }

  @media (max-width: 768px) {
    .dashboard-container {
      padding: 10px;
    }

    .dashboard-header {
      flex-direction: column;
      gap: 10px;
      text-align: center;
    }

    .overview-row .el-col-6 {
      width: 50% !important;
      margin-bottom: 15px;
    }

    .chart-container {
      height: 250px !important;
    }

    .chart-container.large {
      height: 300px !important;
    }
  }
</style>
